package wanxiang

import (
	"fmt"
	"strings"
	"time"
)

type DateRange struct {
	Start time.Time
	End   time.Time
}

// MarshalText implements the [encoding.TextMarshaler] interface.
func (dr DateRange) MarshalText() ([]byte, error) {
	if dr.Start.IsZero() && dr.End.IsZero() {
		return []byte(""), nil
	}
	startTime := dr.Start.Format(time.DateTime)
	endTime := dr.End.Format(time.DateTime)
	return []byte(fmt.Sprintf("%s - %s", startTime, endTime)), nil
}

// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
func (dr *DateRange) UnmarshalText(text []byte) error {
	var err1, err2 error
	if len(text) == 0 {
		dr.Start = time.Time{}
		dr.End = time.Time{}
		return nil
	}
	s := string(text)
	ts := strings.Split(s, " - ")
	if len(ts) != 2 {
		return fmt.Errorf("invalid date range: %s", s)
	}
	dr.Start, err1 = time.Parse(time.DateTime, ts[0])
	dr.End, err2 = time.Parse(time.DateTime, ts[1])
	if err1 != nil || err2 != nil {
		return fmt.Errorf("invalid date format: %s", s)
	}
	return nil
}
